package com.geekgo.method;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author HeHaoyang
 * @version 2016/6/13 16:47
 */
public class RequestToModelUtil {

    public static final <T> T convert(Class<T> clazz, HttpServletRequest request){

        try {
            T obj = clazz.newInstance();
            Set<Method> methodSet = get_mothods(clazz);
            Iterator<Method> methodIterator = methodSet.iterator();
            while(methodIterator.hasNext()){
                Method method = methodIterator.next();
                String methodName = method.getName();
                String key = methodName.substring(3,4).toLowerCase()+methodName.substring(4);
                String value = request.getParameter(key);
                Class<?>[] clazzs = method.getParameterTypes();
                Object[] param_values =new Object[]{TypeParseUtil.convert(value,clazzs[0],null)};
                method.invoke(obj,param_values);
            }
            return obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static final Set<Method> get_mothods(Class<?> clazz){
        Method[] methods = clazz.getMethods();
        Set<Method> methodSet = new HashSet<>();
        for (Method method:methods) {
            if (method.getName().startsWith("set")) methodSet.add(method);
        }
        return methodSet;
    }

}
